package com.it.data_queue;

import java.util.Iterator;

/**
 * @author: Coke
 * @DateTime: 2023/06/11/13:52
 * 环形数组实现队列
 **/
public class ArrayQueue<E> implements Queue<E>, Iterable<E> {
    
    Array<E> array;
    
    public ArrayQueue () {
        array = new Array<>();
    }
    
    public ArrayQueue (int capacity) {
        array = new Array<>(capacity);
    }
    
    @Override
    public boolean offer (E value) {
        if (isFull()) {
            return false;
        }
        array.array[array.tail] = value;
        array.tail = (array.tail + 1) % array.array.length;
        return true;
    }
    
    @Override
    public E pool () {
        if (isEmpty()) {
            return null;
        }
        E a = array.array[array.head];
        array.head = (array.head + 1) % array.array.length;
        return a;
    }
    
    
    @Override
    public E peek () {
        if (isEmpty()) {
            return null;
        }
        return array.array[array.head];
    }
    
    @Override
    public boolean isEmpty () {
        return array.head == array.tail;
    }
    
    @Override
    public boolean isFull () {
        return (array.tail + 1) % array.array.length == array.head;
    }
    
    @Override
    public Iterator<E> iterator () {
        return new Iterator<E>() {
            int p = array.head;
            
            @Override
            public boolean hasNext () {
                return p != array.tail;
            }
            
            @Override
            public E next () {
                E e = array.array[p];
                p = (p + 1) % array.array.length;
                return e;
            }
        };
    }
}
